/* eslint-disable no-lonely-if */

import router from './router'
import initDynamicRouter from 'router/initDynamicRouter'
import { useUserStore } from 'store/modules/user.js'
const whiteList = [`/login`]

// 添加一个状态来跟踪是否已经添加过动态路由
let hasAddedRoutes = false

/**
 * 移除所有的动态路由并重置 hasAddedRoutes 标志
 */
function resetRoutes() {
  const userStore = useUserStore()
  const routes = userStore.getRoutes()
  const accessRoutes = initDynamicRouter.filter((route) => routes.includes(route.name))
  // 移除所有的动态路由
  accessRoutes.forEach((route) => {
    router.removeRoute(route.name)
  })
  // 重置 hasAddedRoutes 标志
  hasAddedRoutes = false
}

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem(`token`)
  const userStore = useUserStore()
  const routes = userStore.getRoutes()
  const accessRoutes = initDynamicRouter.filter((route) => routes.includes(route.name))
  if (token) {
    if (to.path === `/login`) {
      next(`/`)
    } else {
      // 只有当还没有添加过动态路由时，才添加动态路由
      if (!hasAddedRoutes) {
        accessRoutes.forEach((route) => {
          // 标记已经添加过动态路由
          hasAddedRoutes = true

          router.addRoute(route)
        })

        // 重新导航到目标路由，以确保添加的路由能够被访问
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      // 移除所有的动态路由
      resetRoutes()
      next()
    } else {
      // 移除所有的动态路由
      resetRoutes()
      next(`/login`)
    }
  }
})
